import flask
from flask import render_template, request, session
import random
import sqlite3
from flask_wtf import FlaskForm
from wtforms import PasswordField, StringField, SubmitField
from wtforms.validators import DataRequired, EqualTo, Length

app = flask.Flask(__name__, static_url_path='')
app.debug = True
app.secret_key = "ewfe2324rgr23"


class Login(FlaskForm):
    #us = StringField(label=u'用户：', validators=[DataRequired()])
    us = StringField(label='用户：',
                     validators=[DataRequired(message='用户名不能为空'), Length(min=3, max=12, message='长度为6-12')],
                     render_kw={'placeholder':'请输入用户名', 'maxlength':12})
    ps = PasswordField(label=u'密码：', validators=[DataRequired()])
    submit = SubmitField(u'提交')


@app.route("/")
def home():
    form = Login()
    return render_template("login.html", form=form)


@app.route("/info", methods=["POST"])
def login():
    form = Login()
    if form.validate_on_submit():
        cu.execute("select * from  user_info")
        ret = cu.fetchall()
        for i in ret:
            if form.us.data == i[1] and form.ps.data == i[2]:
                break
        else:
            return render_template("login.html", msg='用户名或密码错误', form=form)
        session["user"] = form.us.data
        return render_template("main.html", name=form.us.data)
    else:
        return render_template("login.html", msg='用户名或密码必填')
    # u = request.form.get("username")
    # p = request.form.get("pwd")
    # cu.execute("select * from  user_info")
    # ret = cu.fetchall()
    # for i in ret:
    #     if u == i[1] and p == i[2]:
    #         break
    # else:
    #     return render_template("login.html", msg='用户名或密码错误', form=form)
    # session["user"] = u
    # return render_template("main.html", name=u)


@app.route("/logout", methods=["post"])
def logout():
    form = Login()
    del session["user"]
    return render_template("login.html", form=form)


@app.route("/create", methods=["POST", "GET"])
def create_room():
    # 获取登陆用户
    # session["user"]
    user_name = session.get("user")
    """生成目标数字，创建房间号"""
    # 创建房间号
    room_n = random.randint(1, 20)
    # 生成目标数字
    target_n = random.randint(1, 100)
    cu.execute(
        "insert into guess_num (room, num, owner) VALUES (%d,%d,'%s')" % (room_n, target_n, user_name))
    cu.execute("select room , num , owner from  guess_num")
    ret = cu.fetchall()
    return render_template("main.html", a=ret)


@app.route("/join", methods=["post"])
def online_public():
    """加入房间"""
    # 获取前端页面输入的房间号
    room_number = request.form.get("room_num")
    cu.execute("select * from  guess_num")
    ret = cu.fetchall()
    y = None
    for i in ret:
        if room_number == i[1]:
            y = i[2]
            break
    else:
        return render_template("main.html", msg="房间号不存在")
    return render_template("guess.html", v_y=y)


cx = None
cu = None


@app.before_first_request
def con_db():
    global cx
    global cu
    cx = sqlite3.connect("test.db", check_same_thread=False)
    cu = cx.cursor()


@app.before_request
def before_request():
    form = Login()
    userAg = str(request.user_agent)
    if not userAg.__contains__("Windows"):
        print("非windows操作系统，拒绝访问")
    # 除了登陆请求以外的所有请求验证是否已登录，
    if not request.base_url.__contains__("info"):
        if not session.get("user"):
            return render_template("login.html", form=form)


@app.route("/article", methods=["post"])
def article():
    cu.execute("select * from articles ")
    ret = cu.fetchall()
    return render_template("article.html", c=ret)


@app.route("/publish", methods=["post"])
def publish():
    t = request.form.get("title")
    c = request.form.get("content")

    cu.execute(
        "insert into articles(title, author, content, publishTime) values ('%s','lml','%s',date('now')) " % (t, c))
    cx.commit()
    cu.execute("select * from articles ")
    ret = cu.fetchall()
    return render_template("article.html", c=ret, msg="发表成功")


if __name__ == '__main__':
    print(app.url_map)
    app.run()
